from django.http import HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
from rest_framework.views import APIView
from libs.yuntongxun.sms import CCP
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from verifications.serializers import RegisterSmscodeSerializers

# Create your views here.



"""
前端需要发送给我们一个 uuid,我们接收以后生成一个图片,给前端
1.接收参数uuid
2.生成图片验证码,保存图片验证码数据
3.返回响应

GET   /verifications/imagecodes/(?P<image_code_id>.+)/
"""


class RegisterImageCodeView(APIView):
    def get(self, request, image_code_id):
        # 1.接收参数uuid
        # 2.生成图片验证码,
        text, image = captcha.generate_captcha()
        # 3.保存图片验证码数据到redis
        redis_conn = get_redis_connection('code')
        from . import constant
        redis_conn.setex('img_%s' % image_code_id, constant.IMAGE_CODE_EXPIRE_TIME, text)

        # 4.返回响应
        return HttpResponse(image, content_type='image/jpeg')


"""
    GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx &
    获取短信验证码时,前端将手机号,图片验证码和uuid(image_code_id)发送给后端
    1.接收参数
    2.校验参数
    3.生成短信
    4.发送短信
    5.返回响应
"""


class RegisterSmsCodeView(APIView):
    def get(self, request, mobile):
        # 1.接收参数
        params = request.query_params
        # 2.校验参数
        serializer = RegisterSmscodeSerializers(data=params)
        serializer.is_valid()
        # 3.生成短信
        from random import randint
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)
        # 4保存短信验证码到redis
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        # 5.发送短信
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        from celery_tasks.sms.tasks import send_sms_code
        # delay的参数和send_code任务的参数是对应的
        send_sms_code.delay(mobile,sms_code)
        # 5.返回响应
        return Response({'msg': 'ok'})
